<?php
class ModelCatalogFaq extends Model {
	public function addFaq($data) {
		global $V5_NOW;
		$data['date_added'] = $V5_NOW;
		
		$this->db->insert('faq', $data);
	}

	public function editFaq($faq_id, $data) {
		global $V5_NOW;
		$data['date_modified'] = $V5_NOW;
		$this->db->update('faq', $data, array('faq_id' => $faq_id));
	}

	public function deleteFaq($faq_id) {
		$this->db->delete('faq', array('faq_id' => $faq_id));
	}

	public function getFaq($faq_id) {
		return $this->db->queryOne("SELECT DISTINCT *, (SELECT pd.name FROM @@product_description pd
				WHERE pd.product_id = f.product_id AND pd.language_id = " . (int)C('config_language_id') . ") AS product
				FROM @@faq f WHERE f.faq_id = " . (int)$faq_id);
	}

	public function getFaqs($filter = null) {
		$sql = "SELECT f.*, pd.name FROM
				@@faq f LEFT JOIN @@product_description pd ON (f.product_id = pd.product_id)
				WHERE pd.language_id = " . (int)C('config_language_id');

		if ($filter) {
			if ($filter->get('filter_product_id')) {
				$sql .= " AND f.product_id = " . (int) $filter->get('filter_product_id');
			}
			if ($filter->get('filter_author')) {
				$sql .= " AND f.author = '" . ES($filter->get('filter_author')) . "'";
			}
			if ($filter->get('filter_status') !== null) {
				$sql .= " AND f.status = " . (int) $filter->get('filter_status');
			}
			if ($filter->get('filter_date_added')) {
				$sql .= " AND DATE(f.date_added) = '" . $filter->get('filter_date_added') . "'";
			}
			$sql .= $filter->sort('f.date_added', 'DESC');
			$sql .= $filter->limit();
		}
		$this->log->write($sql);
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getTotalFaqs($filter = null) {
		$sql = "SELECT COUNT(*) AS total FROM @@faq f WHERE 1";
		if ($filter) {
			if ($filter->get('filter_product_id')) {
				$sql .= " AND f.product_id = " . (int) $filter->get('filter_product_id');
			}
			if ($filter->get('filter_author')) {
				$sql .= " AND f.author = '" . ES($filter->get('filter_author')) . "'";
			}
			if ($filter->get('filter_status') !== null) {
				$sql .= " AND f.status = " . (int) $filter->get('filter_status');
			}
			if ($filter->get('filter_date_added')) {
				$sql .= " AND DATE(f.date_added) = '" . $filter->get('filter_date_added') . "'";
			}
		}
		return $this->db->queryOne($sql);
	}

	public function getTotalFaqsAwaitingApproval() {
		return $this->db->queryOne("SELECT COUNT(*) AS total FROM @@faq WHERE status = 0");
	}
}
?>